<template>
	<div class="shopcart-container">
		<!-- 商品列表 -->
		<van-card :price="goodsList.nowprice" :title="goodsList.title" :thumb="APIDomainName + goodsList.pic" :num="1"
			v-if="$route.params.id!=0" />
		<van-card v-for="item in goodsList" :key="item.id" :price="item.nowprice" :title="item.title"
			:thumb="APIDomainName + item.pic" :num="1" v-else />
		<!-- 配送信息 -->
		<!-- <van-cell title="配送服务" label="快递运输,工作日、双休日与节假日均可送货" /> -->
		<van-field v-model="remark" rows="2" autosize label="订单备注" type="textarea" placeholder="请输入订单备注" />
		<!-- 运费信息 -->
		<van-cell title="商品金额" :value="`¥${amount.toFixed(2)}`" />
		<!-- <van-cell title="运费" :value="`¥0.00`" /> -->
		<van-cell title="总价" :value="`¥${amount.toFixed(2)}`" />
		<!-- 创建订单按钮 -->
		<van-button @click="OnClickCreateOrder" size="large" type="primary"
			style="width: 75%;margin: 0 auto;margin-top: 3rem;margin-bottom: 3rem;background-color: #14C5CD;border: 0;"
			round>创建订单</van-button>
	</div>
</template>

<script>
	import {
		createOrderAPI
	} from "@/api/order.js";
	import {
		getCartListCheckedAPI
	} from "@/api/cart.js";
	import {
		getProductDetailByIdAPI,
	} from "@/api/product.js";
	export default {
		data() {
			return {
				goodsList: [],
				remark: "",
				amount: 0,
			};
		},

		created() {
			if (this.$route.params.id != 0) {
				let id = this.$route.params.id;
				getProductDetailByIdAPI(id).then((result) => {
					console.log(result.data);
					this.goodsList = result.data;
					this.amount = this.goodsList.nowprice;
				});
			} else {
				this.initCartListByChecked(); //初始订单商品（购物车勾选商品）
			}

		},

		methods: {
			//初始订单商品（购物车勾选商品）
			initCartListByChecked() {
				getCartListCheckedAPI().then(result => {
					this.goodsList = result.data;
					this.amount = 0;
					this.goodsList.forEach((item) => {
						this.amount += item.nowprice;
					});
				});
			},
			//处理创建订单
			OnClickCreateOrder() {
				let productList = [];
				if (this.$route.params.id != 0) {
					productList.push({
						product_id: this.goodsList.id,
						count: 1,
						price: this.goodsList.nowprice,
					})
				} else {
					this.goodsList.forEach((item) =>
						productList.push({
							product_id: item.product_id,
							count: item.count,
							price: item.nowprice,
						})
					);
				}

				//根据接口文档，准备接口参数
				let params = {
					productList: productList,
					remark: this.remark,
				};
				createOrderAPI(params).then(result => {
					// console.log(result)
					this.$toast(result.msg);
					let id=result.order_id;
					//创建成功后导航到订单列表页面（该页面还未实现）
					this.$router.push({
						name: "orderDetail",
						params: {
							id
						}
					});
				});
			},
		},
	};
</script>

<style lang="less" scoped>
	.shopcart-container {
		display: flex;
		flex-direction: column;
		background: #eee;
		overflow: hidden;
	}

	.van-card__title {
		font-size: 16px;
		margin-top: 1rem;
	}

	.van-card__bottom {
		line-height: 35px;
	}
</style>
